package com.cndym.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;

import com.cndym.cache.XMemcachedClientWrapper;
import com.cndym.constant.Constants;
import com.cndym.service.IFillByYYService;
import com.cndym.utils.DESPlus;
import com.cndym.utils.FillConfigUtils;
import com.cndym.utils.JsonBinder;
import com.cndym.utils.SpringUtils;
import com.cndym.utils.Utils;

/**
 * @author faxc
 * @date 2014-12-19 下午03:10:08
 */
public class CheckFrameWriter extends PrintWriter {
	
	String checkString = "";
	XMemcachedClientWrapper memcachedClientWrapper = (XMemcachedClientWrapper) SpringUtils.getBean("xmemcachedClientWrapper");
	private Logger logger = Logger.getLogger(getClass());

	public CheckFrameWriter(Writer out) {

		super(out);
	}

	String resultString = "";
	char[] data;
	List<Character> list = new ArrayList();
	int i = 0;

	public void write(int c) {

		// System.out.println("111111111111111111");
		try {
			// out.write("2");
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.write((char) c);
	}
	
//	@Override
//	public void flush() {
//		int c=list.size();
//		data=new char[c];
//		for(int i=0;i<c;i++)
//		{
//			data[i]=(char)list.get(i);
//		}
//		super.write("T");
//		super.write(data);
//		super.flush();
//		//String.valueOf(data);
//		
//	};

	public void write(char buf[], int off, int len) {
		System.out.println("22222");
		StringBuffer sb = new StringBuffer(len);
		for (int i = 0; i < len; i++) {
			sb.append(buf[off + i]);
		}
		String s = sb.toString();
		int bodyIndex = s.indexOf("<body>");
		if (bodyIndex > -1) {
			String part1 = s.substring(0, bodyIndex);
			String part2 = s.substring(bodyIndex);
			s = part1 + checkString + part2;
		}
		for (int i = 0; i < s.length(); i++) {
			write(s.charAt(i));
		}
	}

	IFillByYYService fillByYYService = (IFillByYYService) SpringUtils
			.getBean("fillByYYServiceImpl");
	public static boolean IsmemCacheOK = true;
	
	@SuppressWarnings("unchecked")
	public void write(String s, int off, int len) {
		
		Map paraMap = new HashMap<String, String>();
		try {
			paraMap = JsonBinder.buildNormalBinder().getMapper()
					.readValue(s, new TypeReference<Map<String, String>>() {
					});
			if ("0000".equals(paraMap.get("code"))) // 系统正常返回业务值,没有报错
			{
				String innerMsg = paraMap.get("result") + "";
				if (Utils.isNotEmpty(innerMsg) && !"null".equals(innerMsg)) {
					paraMap = JsonBinder.buildNormalBinder().getMapper()
							.readValue(innerMsg, new TypeReference<Map>() {
							});
					if (paraMap.get("userCode") != null
							&& paraMap.get("useAmount") != null) // 系统返回值中含有userCode字段(登录返回)
																	// ;
																	// 根据useAmount是否存在,判断是否为登录或注册接口
					{
						try {
							String token_exp_minute = FillConfigUtils
									.getValue("TOKEN_EXP_MINUTE");
							long l = Utils.addDate(new Date(), "f",
									Integer.parseInt(token_exp_minute))
									.getTime();
							paraMap.put("token", new DESPlus().encrypt(paraMap.get("userCode")+ "_" + System.currentTimeMillis() + "_" + l));

							logger.info("userCode: " + paraMap.get("userCode")
									+ " token: " + paraMap.get("token"));
							if (memcachedClientWrapper.get(paraMap.get("userCode") + "") != null) // 在token有效期内再次登录
							{
								try {
									if (IsmemCacheOK)
										memcachedClientWrapper.delete(memcachedClientWrapper.get(paraMap.get("userCode") + "")+ "");
								} catch (Exception e) {
									IsmemCacheOK = false;
									logger.error("memCached挂了", e);
								}
								fillByYYService.updateBySQL(
										"DELETE FROM TOKEN_USERCODE_MAPPING WHERE TOKEN=?",
												new String[] { memcachedClientWrapper.get(paraMap.get("userCode") + "") });
								fillByYYService.updateBySQL(
										"delete from USERCODE_TOKEN_MAPPING where user_code=?",
												new String[] { paraMap.get("userCode") + "" });
							} else {
								// 如果是没有登录过(表中没有记录,删除行数为0)
								fillByYYService.updateBySQL(
										"delete from TOKEN_USERCODE_MAPPING where token in (select token from  USERCODE_TOKEN_MAPPING where user_code=?)",
												new String[] { paraMap.get("userCode") + "" });
								fillByYYService.updateBySQL(
										"delete from USERCODE_TOKEN_MAPPING where user_code=?",
												new String[] { paraMap.get("userCode") + "" });
							}
							try {
								if (IsmemCacheOK)
									memcachedClientWrapper.set(paraMap.get("token") + "",
													60 * Integer.parseInt(token_exp_minute),
													paraMap.get("userCode")+ "");// 10分钟有效
							} catch (Exception e) {
								// 捕获memcached服务挂掉
								IsmemCacheOK = false;
								logger.error("memCached挂了", e);

							}

							fillByYYService.updateBySQL(
									"INSERT /*No+ APPEND */ INTO TOKEN_USERCODE_MAPPING(ID,TOKEN, USER_CODE) VALUES(SEQ_TOKEN_USERCODE_MAPPING.NEXTVAL,?,?)",
											new String[] {paraMap.get("token") + "", paraMap.get("userCode") + "" });

							List list = fillByYYService.getListBySQL(
									"SELECT USER_CODE FROM USERCODE_TOKEN_MAPPING WHERE USER_CODE=?",
											new String[] { paraMap.get("userCode") + "" });
							if (list.size() > 0) {
								fillByYYService.updateBySQL(
									"update USERCODE_TOKEN_MAPPING set token=? where user_code=?",
											new String[] {paraMap.get("token")+ "", paraMap.get("userCode") + "" });
							} else {
								fillByYYService.updateBySQL(
									"INSERT /*No+ APPEND */ INTO USERCODE_TOKEN_MAPPING(ID,USER_CODE,TOKEN) VALUeS(SEQ_USERCODE_TOKEN_MAPPING.NEXTVAL,?,?)",
											new String[] {paraMap.get("userCode") + "", paraMap.get("token") + "" });
							}
							try {
								if (IsmemCacheOK)
									memcachedClientWrapper.set(paraMap.get("userCode") + "",
													60 * Integer.parseInt(token_exp_minute),
													paraMap.get("token") + "");
							} catch (Exception e) {
								// 捕获memcached服务挂掉
								IsmemCacheOK = false;
								logger.error("memCached挂了", e);
							}
							//memcachedClientWrapper.delete(paraMap.get("token"));
						} catch (Exception e) {
							logger.error("Exception", e);

						}
						// paraMap.remove("userCode");
					}

					s = JsonBinder.buildNonDefaultBinder().toJson(paraMap);
					paraMap = new HashMap<String, String>();
					paraMap.put("result", s);
					paraMap.put("code", "0000");
					//paraMap.put("msg", "系统处理成功");

					s = JsonBinder.buildNonDefaultBinder().toJson(paraMap);
				}
			}
		} catch (JsonParseException e) {
			logger.error("", e);
			e.printStackTrace();
		} catch (JsonMappingException e) {
			logger.error("", e);
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("", e);
			e.printStackTrace();
		}
		for (int i = 0; i < s.length(); i++) {
			write(s.charAt(off + i));
		}
	}
	
	public static void main(String args[])
	{
		 XMemcachedClientWrapper memcachedClientWrapper = (XMemcachedClientWrapper) SpringUtils.getBean("xmemcachedClientWrapper");
		 String s=memcachedClientWrapper.get("20141103165216867853");
		 System.out.println(s);
		 
	}
	}

